package com.ErpCoreWeb.Report;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Report.CReport;
import com.ErpCoreModel.Report.CStatItem;
import com.ErpCoreModel.Report.enumItemType;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class SelStatItem
 */
@WebServlet("/SelStatItem")
public class SelStatItem extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;
	
    public CTable m_Table = null;
    public CCompany m_Company = null;
    public CReport m_Report = null; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelStatItem() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		try {

	        String B_Company_id = request.getParameter("B_Company_id");
			if (Global.IsNullParameter(B_Company_id))
				m_Company = Global.GetCtx(this.getServletContext())
						.getCompanyMgr().FindTopCompany();
			else
				m_Company = (CCompany) Global.GetCtx(this.getServletContext())
						.getCompanyMgr().Find(Util.GetUUID(B_Company_id));
			

			String rptid = request.getParameter("rptid");
	        if (Global.IsNullParameter(rptid))
	        {
	            response.getWriter().close();
	            return;
	        }
	        m_Report = (CReport)m_Company.getReportMgr().Find(Util.GetUUID(rptid));
	        if (m_Report == null) //可能是新建的
	        {
	            if (request.getSession().getAttribute("AddReport") == null)
	            {
		            response.getWriter().close();
	                return;
	            }
	            m_Report = (CReport)request.getSession().getAttribute("AddReport");
	        }
	        if (m_Report.getStatItemMgr().GetList().size() > 0)
	        {
	            CStatItem StatItem = (CStatItem)m_Report.getStatItemMgr().GetList().get(0);
	            m_Table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(StatItem.getFW_Table_id());
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetColumnData"))
        {
        	GetColumnData();
            return ;
        }
        else if (Action.equalsIgnoreCase("GetStatItemData"))
        {
        	GetStatItemData();
            return ;
        }
        else if (Action.equalsIgnoreCase("AddStatItem"))
        {
        	AddStatItem();
            return ;
        }
        else if (Action.equalsIgnoreCase("DeleteStatItem"))
        {
        	DeleteStatItem();
            return ;
        }
        else if (Action.equalsIgnoreCase("AddFormula"))
        {
        	AddFormula();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
            m_Report.getStatItemMgr().Cancel();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }

		
	}

    void GetColumnData()
    {
        String Table_id = request.getParameter("Table_id");
        if (Global.IsNullParameter(Table_id))
            return;
        CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(Util.GetUUID(Table_id));
        if (table == null)
            return;

        List<CBaseObject> lstObj = table.getColumnMgr().GetList();
        String sData = "";
        for (CBaseObject obj : lstObj)
        {
            CColumn column = (CColumn)obj;
            
            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\" },"
                , column.getId().toString()
                , column.getName());
        }

		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, lstObj.size());

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void GetStatItemData()
    {
        List<CBaseObject> lstObj = m_Report.getStatItemMgr().GetList();

        String sData = "";
        int iCount = 0;
        for (CBaseObject obj : lstObj)
        {
            CStatItem StatItem = (CStatItem)obj;

            String sTableName = "", sColumnName = "";
            if (StatItem.getItemType() == enumItemType.Field)
            {
                CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(StatItem.getFW_Table_id());
                if (table != null)
                {
                    sTableName = table.getName();
                    CColumn column = (CColumn)table.getColumnMgr().Find(StatItem.getFW_Column_id());
                    if (column != null)
                        sColumnName = column.getName();
                }
            }
            else
            {
                sTableName = StatItem.getName();
                sColumnName = StatItem.getFormula();
            }

            sData += String.format("{ \"id\": \"%s\",\"FW_Table_id\":\"%s\",\"TableName\":\"%s\",\"FW_Column_id\":\"%s\", \"ColumnName\":\"%s\", \"StatType\":\"%d\", \"Idx\":\"%d\" },"
                , StatItem.getId().toString()
                , StatItem.getFW_Table_id().toString()
                , sTableName
                , StatItem.getFW_Column_id().toString()
                , sColumnName
                , StatItem.getStatType().ordinal()
                , StatItem.getIdx());
            iCount++;
        }
		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void AddStatItem()
    {
		try {
			String Table_id = request.getParameter("Table_id");
			if (Global.IsNullParameter(Table_id)) {
				response.getWriter().print("表不存在！");
				return;
			}
			CTable table = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(Util.GetUUID(Table_id));
			if (table == null) {
				response.getWriter().print("表不存在！");
				return;
			}
			String Column_id = request.getParameter("Column_id");
			if (Global.IsNullParameter(Column_id)) {
				response.getWriter().print("字段不存在！");
				return;
			}
			CColumn column = (CColumn) table.getColumnMgr().Find(
					Util.GetUUID(Column_id));
			if (column == null) {
				response.getWriter().print("字段不存在！");
				return;
			}
			if (m_Report.getStatItemMgr().FindByColumn(table.getId(),
					column.getId()) != null) {
				response.getWriter().print("指标已经存在！");
				return;
			}

			CStatItem StatItem = new CStatItem();
			StatItem.Ctx = Global.GetCtx(this.getServletContext());
			StatItem.setRPT_Report_id(m_Report.getId());
			StatItem.setFW_Table_id(table.getId());
			StatItem.setFW_Column_id(column.getId());
			StatItem.setName(column.getName());
			StatItem.setIdx(m_Report.getStatItemMgr().GetList().size());

			CUser user = (CUser) request.getSession().getAttribute("User");
			StatItem.setCreator(user.getId());

			m_Report.getStatItemMgr().AddNew(StatItem);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void DeleteStatItem()
    {
        String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
        	try {
				response.getWriter().print("请选择指标！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        m_Report.getStatItemMgr().Delete(Util.GetUUID(delid));
    }
    void AddFormula()
    {
		try {
			String AsName = request.getParameter("AsName");
			if (Global.IsNullParameter(AsName)) {
				response.getWriter().print("别名不能空！");
				return;
			}
			String Formula = request.getParameter("Formula");
			if (Global.IsNullParameter(Formula)) {
				response.getWriter().print("公式不能空！");
				return;
			}

			CStatItem StatItem = new CStatItem();
			StatItem.Ctx = Global.GetCtx(this.getServletContext());
			StatItem.setRPT_Report_id(m_Report.getId());
			StatItem.setItemType(enumItemType.Formula);
			StatItem.setName(AsName);
			StatItem.setFormula(Formula);

			CUser user = (CUser) request.getSession().getAttribute("User");
			StatItem.setCreator(user.getId());

			m_Report.getStatItemMgr().AddNew(StatItem);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void PostData()
    {
    }
}
